package com.gaowl.yygh.user.api;

import com.alibaba.excel.util.StringUtils;
import com.alibaba.fastjson.JSONObject;
import com.gaowl.yygh.commom.helper.JwtHelper;
import com.gaowl.yygh.commom.result.Result;
import com.gaowl.yygh.model.user.UserInfo;
import com.gaowl.yygh.user.service.UserInfoService;
import com.gaowl.yygh.user.utils.HttpClientUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/api/ucenter/wx")
public class WeixinApiController {

    @Autowired
    private UserInfoService userInfoService;

    String WX_OPEN_APP_ID = "wxed9954c01bb89b47";
    String WX_OPEN_APP_SECRET = "a7482517235173ddb4083788de60b90e";
    String WX_OPEN_REDIRECT_URL = "http://guli.shop/api/ucenter/wx/callback";
    String YYGH_BASE_URL = "http://localhost:3000";

    /**
    * @Description: 生成微信登录二维码
    * @Param:
    * @return: 生成二维码需要的参数（Map封装）
    * @Author: gaowl@stu.jiangnan.edu.cn
    * @Date: 2021/04/06
    */
    @GetMapping("getLoginParam")
    @ResponseBody
    public Result genQrConnect() {
        try {
            Map<String, Object> map = new HashMap<>();
            map.put("appid", WX_OPEN_APP_ID);
            map.put("scope",  "snsapi_login");
            map.put("redirect_uri", URLEncoder.encode(WX_OPEN_REDIRECT_URL, "utf-8"));
            map.put("state", System.currentTimeMillis()+"");
            return Result.ok(map);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return null;
        }
    }


    /**
    * @Description: 用户扫描 微信登录二维码 后的回调函数
    * @Param: code
    * @return: 
    * @Author: gaowl@stu.jiangnan.edu.cn
    * @Date: 2021/04/06
    */
    @GetMapping("callback")
    //@ResponseBody
    public String callback(String code, String state) throws Exception {
        //
        System.out.println(code);
        // 使用code、appId和appSecret获取access_token
        String baseAccessTokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token" +
                "?appid=%s" +  "&secret=%s" +   "&code=%s" +   "&grant_type=authorization_code";
        String accessTokenUrl = String.format(baseAccessTokenUrl,
                WX_OPEN_APP_ID, WX_OPEN_APP_SECRET, code);

        // 使用http client请求这个地址
        String accessTokenInfo = HttpClientUtils.get(accessTokenUrl);
        System.out.println(accessTokenInfo);

        // 解析accessTokenInfo获得access_token和open_id
        JSONObject jsonObject = JSONObject.parseObject(accessTokenInfo);
        String access_token = jsonObject.getString("access_token");
        String open_id = jsonObject.getString("open_id");

        // 根据openId判断该用户是否已经存在于数据库中
        UserInfo userInfo = userInfoService.selectWxInfoOpenId(open_id);
        if (userInfo == null) {
            // 如果用户微信信息不存在，通过openid和access_token请求微信地址，得到扫描人信息
            String baseUserInfoUrl = "https://api.weixin.qq.com/sns/userinfo" +
                    "?access_token=%s" +  "&openid=%s";
            String userInfoUrl = String.format(baseUserInfoUrl, access_token, open_id);
            String resultInfo = HttpClientUtils.get(userInfoUrl);
            System.out.println(resultInfo);

            // 解析用户信息(用户昵称、头像)
            JSONObject resultUserInfoJson = JSONObject.parseObject(resultInfo);
            String nickname = resultUserInfoJson.getString("nickname");
            System.out.println(open_id);
            open_id = resultUserInfoJson.getString("openid");

            // 设置用户信息，并添加到数据库中
            userInfo = new UserInfo();
            userInfo.setNickName(nickname);
            userInfo.setOpenid(open_id);
            userInfo.setStatus(1);
            userInfoService.save(userInfo);
        }

        // ======= 返回name和token字符串 =========
        Map<String, String> map = new HashMap<>();
        String name = userInfo.getName();
        if (StringUtils.isEmpty(name)){  //
            name = userInfo.getNickName();
        }
        map.put("name", name);
        //判断userInfo是否有手机号，如果手机号为空，返回openid；非空，则返回空字符串
        //之后前端根据openId来确定是否需要绑定手机号：openID非空，绑定手机号;空，则不需要绑定手机号
        if(StringUtils.isEmpty(userInfo.getPhone())) {
            map.put("openid", userInfo.getOpenid());
        } else {
            map.put("openid", "");
        }
        // 使用jwt生成token字符串
        String token = JwtHelper.createToken(userInfo.getId(), name);
        map.put("token", token);

        System.out.println(userInfo.getOpenid());
        System.out.println(map);

        // 跳转到前端页面
        return "redirect:" + YYGH_BASE_URL
                + "/weixin/callback?token=" + map.get("token")
                + "&openid=" + map.get("openid")
                + "&name=" + URLEncoder.encode(map.get("name"),"utf-8");
    }
}
